package com.sw.study.web.util;

import java.util.HashMap;

/**
 * 请求上下文
 */
public class RequestContext {
    private static ThreadLocal<RequestContext> threadLocal=new ThreadLocal<>();
    private HashMap<String,Object>  context;

    /**
     * 初始化全局唯一
     */

    /**
     * 获取上下文实例对象
     * @return
     */
    public static RequestContext getContext(){
        if (threadLocal.get() == null) {
            threadLocal.set(new RequestContext());
        }
        return (RequestContext)threadLocal.get();
    }

    /**
     * 放数据
     * @param key
     * @param value
     */
    public void setObject(String key, Object value) {
        if (this.context == null) {
            this.context = new HashMap();
        }

        this.context.put(key, value);
    }

    /**
     * 销毁当前
     */
    public void destory() {
        if (this.context != null) {
            this.context.clear();
            threadLocal.remove();
        }
    }

    /**
     * 取值
     * @param key
     * @return
     */
    public Object getObject(String key)  {
        if (this.context == null) {
            return null;
        } else {
            return this.context.get(key);
        }
    }
}
